package com.mingtu.jgspatrol.activity;

import static com.mingtu.jgspatrol.utils.MyConstant.animationType;
import static com.mingtu.jgspatrol.utils.MyConstant.isFirstOnly;
import static com.mingtu.jgspatrol.utils.MyConstant.isOpenLoadAnimation;

import android.content.Intent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseBindingActivity;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.CarInfoListAdapter;
import com.mingtu.jgspatrol.bean.WhiteListBean;
import com.mingtu.jgspatrol.databinding.ActivityParkWhiteListBinding;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.mingtu.jgspatrol.view.ParkFilterView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;

public class ParkWhiteListActivity extends BaseBindingActivity<ActivityParkWhiteListBinding> {

    private int currentPage = 1;
    private boolean isLoadMore = true;
    private CarInfoListAdapter carInfoListAdapter;
    private String parkCode;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_park_white_list;
    }

    @Override
    protected void initView() {
        setModuleTitle("白名单管理");
        setDarkThemeStatusBar();


        LinearLayoutManager manager = new LinearLayoutManager(context);
        binding.recycler.setLayoutManager(manager);
        binding.recycler.addItemDecoration(new BottomSpaceItemDecoration());

        addClickListener(this, binding.ivAdd);

    }

    @Override
    protected void initData() {
        initListener();

        carInfoListAdapter = new CarInfoListAdapter();
        binding.recycler.setAdapter(carInfoListAdapter);
        if (isOpenLoadAnimation) {
            carInfoListAdapter.isFirstOnly(isFirstOnly);
            carInfoListAdapter.openLoadAnimation(animationType);
        }
        carInfoListAdapter.setEmptyView(new EmptyDataLayout(context));
        carInfoListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_delete: //删除白名单
                        new XPopup.Builder(ParkWhiteListActivity.this)
                                .isDestroyOnDismiss(true)
                                .dismissOnTouchOutside(true)
                                .hasShadowBg(true)
                                .asConfirm(context.getResources().getString(com.mingtu.infrared.R.string.text_tip), "确定删除吗？",
                                        context.getResources().getString(com.mingtu.infrared.R.string.text_cancle), context.getResources().getString(com.mingtu.infrared.R.string.text_sure),
                                        new OnConfirmListener() {
                                            @Override
                                            public void onConfirm() {
                                                WhiteListBean.PageBean.ListBean listBean = carInfoListAdapter.getData().get(position);
                                                int id = listBean.getId();
                                                deleteData(id, position);
                                            }
                                        }, null, false)
                                .show();
                        break;
                }
            }
        });
        binding.parkFilterView.setOnSelectResultListener(new ParkFilterView.OnSelectResultListener() {
            @Override
            public void onResult(String code) {
                parkCode = code;
                getListData(1);
            }
        });
        addClickListener(this, binding.ivAdd);
    }

    @Override
    protected void getData() {

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_add:
                IntentUtils.getInstance().readyGoForResult(ParkWhiteListActivity.this, ParkAddWhiteListActivity.class, 100);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == 200) {
            getListData(1);
        }
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                binding.srlUp.setNoMoreData(false);
                currentPage = 1;
                getListData(1);
            }
        });
    }

    private void initLoadMoreListener() {
        binding.srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(carInfoListAdapter.getData(), Constant.PAGE_SIZE);
                    getListData(currentPage);
                }
                binding.srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }


    /**
     * 白名单列表
     */
    private void getListData(int pageNum) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("parkCode", parkCode);
        MyUtills.removeMapNull(hashMap);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_WHITE_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(ActivityUtils.getTopActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            WhiteListBean whiteListBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                whiteListBean = new WhiteListBean();
                                whiteListBean = gson.fromJson(result, WhiteListBean.class);
                                List<WhiteListBean.PageBean.ListBean> dataBeans = whiteListBean.getPage().getList();
                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            carInfoListAdapter.replaceData(dataBeans);
                                        } else {
                                            carInfoListAdapter.addData(dataBeans);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));

                            }

                        }
                    }
                });

    }

    /**
     * 删除白名单
     */
    private void deleteData(int id, int position) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("chargeId", id);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_DELETE_WHITE_LIST + "/" + id)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(ActivityUtils.getTopActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("删除成功！");
                                //刷新列表
                                carInfoListAdapter.remove(position);
                            }
                        }
                    }
                });

    }
}
